/**
 * Copyright(C) 2019 FUYUN DATA SERVICES CO.,LTD. - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * 该源代码版权归属福韵数据服务有限公司所有
 * 未经授权，任何人不得复制、泄露、转载、使用，否则将视为侵权
 */

import { createModel } from "@rematch/core";
import { IRootState } from "../../store";
import {
  getProductList,
  saveProduct,
  getProductById,
  editProduct,
  deleteProduct
} from "src/pages/Product/components/productManage/ProductAPI";
import { message } from "antd";

export interface IProduct {
  id: string;
  name: string;
  description: string;
  status: string;
  createTime: string;
  modifyTime: string;
}

interface IState {
  productList: IProduct[];
  productById: IProduct | null;
  pageTotal: number;
}

const initalState: IState = {
  productList: [],
  productById: null,
  pageTotal: 0
};

export interface ITagList {
  id: string;
  name: string;
}

export const product = createModel({
  state: initalState,
  reducers: {
    setProductList: (state: IState, payload): IState => {
      return { ...state, productList: payload };
    },
    setProductById: (state: IState, payload): IState => {
      return { ...state, productById: payload };
    }
  },
  effects: dispatch => ({
    async getProductList(payload: any, rootState: IRootState) {
      const res = await getProductList(payload);
      if (res.status !== 200) {
        return;
      }
      initalState.pageTotal = res.data.totalElements;
      await dispatch.product.setProductList(res.data.content);
    },
    async getProductById(payload: any, rootState: IRootState) {
      const res = await getProductById(payload);
      if (res.status !== 200) {
        return;
      }
      payload.callback(res.data);
      await dispatch.product.setProductById(res.data);
    },
    async saveProduct(payload: any, rootState: IRootState) {
      const res = await saveProduct(payload);
      if (res.status !== 200) {
        message.warning(res.message);
        return;
      }
      message.success("保存成功!");
    },
    async editProduct(payload: any, rootState: IRootState) {
      const res = await editProduct(payload);
      if (res.status !== 200) {
        message.warning(res.message);
        return;
      }
      message.success("保存成功!");

      dispatch.product.getProductList({
        page: 0,
        name: ""
      });
    },
    async deleteProduct(id: string, rootState: IRootState) {
      const res = await deleteProduct(id);
      if (res.status !== 200) {
        return;
      }
      message.success("删除成功!");
      dispatch.product.getProductList({
        page: 0,
        name: ""
      });
    }
  })
});
